﻿# encoding:utf-8
# 批量替换文件夹下所有文件内容
# https://www.jianshu.com/p/be4b5f1742cc

import os
import re
# 遍历目录下所有文件
fileDir = "D:\\code\\java\\gacrnd_new"
# 文件内容大小写敏感，是依次替换
replace_list1 = [  # [oldvalue,newcalue]
    ["http://10.123.1.8/", "https://gacrnd-gitlab.gacicv.com/"],
    # ["A", "T"],
    # ["V", "H"],
    # ["a", "ON"]
]
# 文件名称大小写敏感，是依次替换
# replace_list2 = [  # [oldvalue,newcalue]
#     ["2018-07-30", "2019-01-02"],
#     ["20180730", "20190102"]  # ,
# ]
# 获取目录下所有文件目录+名称


def listFiles(dirPath, fileNameRegex=None):
    fileList = []
    if fileNameRegex is None:
        for root, dirs, files in os.walk(dirPath):
            for fileObj in files:
                if fileNameRegex is None:
                    fileList.append(os.path.join(
                        root, fileObj).replace("\\", "/"))
    else:
        for root, dirs, files in os.walk(dirPath):
            for fileObj in files:
                if re.match(fileNameRegex, fileObj):
                    fileList.append(os.path.join(
                        root, fileObj).replace("\\", "/"))
    return fileList
# 替换内容


def replace_content():
    fileList = listFiles(fileDir, 'pom.xml')
    print('replace_content: '+str(len(fileList)))
    encode = 'UTF-8'
    for fileObj in fileList:
        fin = open(fileObj, mode='rt', newline='',
                   encoding=encode)  # newline=''表示不更改换行符
        data = fin.read()
        fin.close()

        needWrite = False
        for rp in range(len(replace_list1)):
            if replace_list1[rp][0] in data:
                needWrite = True
                break

        if needWrite:
            fout = open(fileObj, mode='wt', newline='',
                        encoding=encode)
            for rp in range(len(replace_list1)):
                if replace_list1[rp][0] in data:
                    data = data.replace(
                        replace_list1[rp][0], replace_list1[rp][1])

            fout.write(data)
            fout.close()
            print('replace_content write: '+fileObj)


# def replace_filename():
#     fileList = listFiles(fileDir)
#     for fileObj in fileList:
#         newname = fileObj
#         for rp2 in range(len(replace_list2)):
#             newname = newname.replace(
#                 replace_list2[rp2][0], replace_list2[rp2][1])
#         os.rename(fileObj, newname)
#         print(newname)


# 运行
if __name__ == '__main__':
    replace_content()
    # replace_filename()
